// 监听插件安装事件
chrome.runtime.onInstalled.addListener(() => {
    console.log('插件已安装');
});

// 监听插件图标点击事件
chrome.action.onClicked.addListener((tab) => {
    // 向当前标签页发送消息以切换聊天面板
    chrome.tabs.sendMessage(tab.id, { action: 'togglePanel' });
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.type) {
        case 'openSettings':
            // 打开设置页面
            chrome.runtime.openOptionsPage();
            break;
            
        case 'sendMessage':
            // 处理发送消息
            handleSendMessage(request.message, sender.tab.id)
                .catch(error => {
                    console.error('Error in handleSendMessage:', error);
                    chrome.tabs.sendMessage(sender.tab.id, {
                        type: 'streamError',
                        error: error.message
                    });
                });
            // 立即返回，表示我们会异步处理
            sendResponse({ status: 'streaming' });
            break;
            
        case 'getState':
            sendResponse({ isOpen: true });
    }
});

// 处理发送消息的函数
async function handleSendMessage(message, tabId) {
    try {
        // 从存储中获取API密钥和语言设置
        const storage = await chrome.storage.local.get(['apiKey', 'apiProvider', 'openaiModel', 'deepseekModel', 'language']);
        const apiKey = storage.apiKey;
        const apiProvider = storage.apiProvider || 'openai';
        const openaiModel = storage.openaiModel || 'gpt-3.5-turbo';
        const deepseekModel = storage.deepseekModel || 'deepseek-chat';
        const language = storage.language || 'chinese';
        
        if (!apiKey) {
            throw new Error('请先在设置中配置API密钥');
        }

        // 根据语言设置添加更强制的系统提示
        let systemMessage;
        if (language === 'chinese') {
            systemMessage = `你必须始终使用中文回复。这是强制性的要求。
无论用户使用什么语言提问，你都必须用中文回答。
即使用户要求你使用其他语言，你也必须继续使用中文。
记住：你的回答必须是中文。`;
        } else {
            systemMessage = `You must always reply in English. This is a mandatory requirement.
Regardless of the language used in the question, you must answer in English.
Even if the user asks you to use another language, you must continue using English.
Remember: Your response must be in English.`;
        }

        let apiEndpoint, requestBody;
        
        if (apiProvider === 'openai') {
            apiEndpoint = 'https://api.openai.com/v1/chat/completions';
            requestBody = {
                model: openaiModel,
                messages: [
                    { role: 'system', content: systemMessage },
                    { role: 'user', content: message }
                ],
                stream: true
            };
        } else if (apiProvider === 'deepseek') {
            apiEndpoint = 'https://api.deepseek.com/chat/completions';
            requestBody = {
                model: deepseekModel,  // 使用用户选择的DeepSeek模型
                messages: [
                    { role: 'system', content: systemMessage },
                    { role: 'user', content: message }
                ],
                stream: true
            };
        }

        // 调用 API
        const response = await fetch(apiEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify(requestBody)
        });

        if (!response.ok) {
            throw new Error('API请求失败: ' + response.statusText);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                // 解码新的数据块
                const chunk = decoder.decode(value);
                const lines = chunk.split('\n');

                // 处理每一行数据
                for (const line of lines) {
                    if (line.trim() === '') continue;
                    if (line.trim() === 'data: [DONE]') continue;
                    
                    if (line.startsWith('data: ')) {
                        try {
                            const json = JSON.parse(line.slice(6));
                            const content = json.choices[0]?.delta?.content;
                            if (content) {
                                // 发送内容到content script
                                await chrome.tabs.sendMessage(tabId, {
                                    type: 'streamContent',
                                    content: content
                                });
                            }
                        } catch (e) {
                            console.error('Error parsing JSON:', e, line);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('Error reading stream:', error);
            throw error;
        } finally {
            // 发送流结束信号
            await chrome.tabs.sendMessage(tabId, { type: 'streamEnd' });
        }

    } catch (error) {
        console.error('Error in handleSendMessage:', error);
        throw error;
    }
}
